package org.ljy.forum6.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.ljy.forum6.common.AppConfig;
import org.ljy.forum6.common.AppResult;
import org.ljy.forum6.common.ResultCode;
import org.ljy.forum6.exception.ApplicationException;
import org.ljy.forum6.model.User;
import org.ljy.forum6.services.impl.UserServiceImpl;
import org.ljy.forum6.utils.MD5Util;
import org.ljy.forum6.utils.StringUtil;
import org.ljy.forum6.utils.UUIDUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "用户接口")
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

    @Resource
    private UserServiceImpl userService;

    /**
     * 用户注册
     * @param username 用户名
     * @param nickname 用户昵称
     * @param password 用户密码
     * @param passwordRepeat 确认密码
     * @return 统一返回结果
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("用户昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("用户密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("用户确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        log.info("用户注册,controller");
        //1.参数校验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(nickname)
                || StringUtil.isEmpty(password) || StringUtil.isEmpty(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        if(!password.equals(passwordRepeat)) {
            log.error(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME));
        }
        //2.数据准备
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //准备盐等操作
        String salt = UUIDUtil.UUID_32();
        String encryPassword = MD5Util.madSalt(password,salt);
        user.setPassword(encryPassword);
        user.setSalt(salt);
        //3.调用service层
        userService.createNormalUser(user);
        return AppResult.success();
    }

    /**
     * 用户登陆
     * @param request 请求自带
     * @param username 用户名
     * @param password 用户密码
     * @return 统一返回
     */

    @ApiOperation("用户登陆")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @RequestParam("username") @ApiParam("用户名") @NonNull String username,
                           @RequestParam("password") @ApiParam("用户密码") @NonNull String password) {
        //1.参数校验 -- 注解已完成
        //2.调用service层
        User user = userService.login(username, password);
        //3.设置session
        HttpSession session = request.getSession(true);//true-没有session则创建,有则返回 false - 没有也不创建
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success();
    }

    /**
     * 获取用户详情页
     * @param request 获取id
     * @param id 参数可传id
     * @return 返回用户对象
     */
    @ApiOperation("查询用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id) {
        log.info("获取用户信息");
        User user = null;
        if(id != null) {
            //1.参数有id
            user = userService.selectById(id);
        }else {
            //2.参数不传id
            log.info("======================我走到这一步了1111");
            HttpSession session = request.getSession(false);
            System.out.println("session"+session.getId());
          /*  if(session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
                //用户未登录
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }*/
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }
        if(user == null) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        return AppResult.success(user);
    }

    /**
     * 退出登陆
     * @param request 用于获取用户信息
     * @return 统一返回
     */
    @ApiOperation("退出登录")
    @GetMapping("/")
    public AppResult logout(HttpServletRequest request) {
        //1.获取session
        HttpSession session = request.getSession(false);
        if(session != null) {
            //2.注销session
            log.info("退出登录");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                @ApiParam("用户昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                @ApiParam("用户性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @ApiParam("用户邮箱") @RequestParam(value = "email",required = false) String email,
                                @ApiParam("用户电话") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @ApiParam("用户简介") @RequestParam(value = "remark",required = false) String remark) {
        //1.参数全null校验
        if(username == null && nickname == null && gender == null && email == null
                && phoneNum == null && remark == null) {
            log.warn("传入的参数全null");
            return AppResult.failed("请输入要修改的值");
        }
        //2.获取旧对象
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //3.封装新对象
        User updateUser = new User();
        updateUser.setId(user.getId());//用户Id
        updateUser.setUsername(username);//用户名
        updateUser.setNickname(nickname);//用户昵称
        updateUser.setGender(gender);//性别
        updateUser.setEmail(email);//邮箱
        updateUser.setPhoneNum(phoneNum);//电话号码
        updateUser.setRemark(remark);//个人简介
        //4.调用service
        userService.modifyInfo(updateUser);
        //5.重新设置session
        user = userService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION, user);
        //5.返回结果
        return AppResult.success();
    }

    /**
     * 用户修改密码
     * @param request 用于获取用户id
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @param passwordRepeat 确认密码
     * @return
     */
    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult  modifyPassword(HttpServletRequest request,
                                     @ApiParam("旧密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                     @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                     @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        //1.校验密码
        if(!newPassword.equals(passwordRepeat)) {
            log.warn("两次输入的密码不相同");
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //2.获取对象id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        User existUser = userService.selectById(user.getId());
        if(existUser == null || existUser.getState()==1 || existUser.getDeleteState()==1) {
            log.warn("用户不正常");
            throw new ApplicationException(AppResult.failed());
        }
        //3.调用service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        //4.销毁session
        if(session != null) {
            session.invalidate();
        }
        return AppResult.success();
    }


}
